const express = require("express");
const { getTotal, getFirstPageRecentUpdates } = require("./src");
const { to } = require("await-to-js");
const path = require("path");
const fs = require("fs");
const httpProxy = require("express-http-proxy");
// import {fileTypeFromFile} from 'file-type';
// const mime = require("file-type/index.js");

// console.log(mime);

const app = express();
const port = 3000;

const htmlPath = path.join(__dirname, "./client");
const contentType = {
  ".js": "application/javascript;charset=utf8",
};
app.use((req, res, next) => {
  res.setHeader("Content-Type", "application/json;charset=utf8");
  next();
});

app.use("/api/", httpProxy("http://localhost:8080/api/"));

app.all("/static/*", (req, res) => {
  const { url, query, path } = req;

  const filePath = htmlPath + path;
  console.log(filePath);
  console.log(query);
  if (fs.existsSync(filePath)) {
    // const contentType0 = mime.lookup(filePath);
    // res.setHeader("Content-Type", contentType0);
    const content = fs.readFileSync(filePath);
    res.send(content);
    return;
  }
  res.sendStatus("404");
});

app.all("/h5_files/*", (req, res) => {
  const { url, query, path } = req;

  const filePath = htmlPath + path;
  if (fs.existsSync(filePath)) {
    // const contentType0 = mime.lookup(filePath);
    // res.setHeader("Content-Type", contentType0);
    const content = fs.readFileSync(filePath);
    res.send(content);
    return;
  }
  res.sendStatus("404");
});

function getHtml(req, res) {
  const { url, query, path } = req;

  const readHtmlPath = htmlPath + path;

  // const mimeType = getType(readHtmlPath);
  // console.log(mimeType);
  res.setHeader("Content-Type", "text/html;charset=utf8");

  console.log(readHtmlPath);
  const html = fs.readFileSync(readHtmlPath);
  res.send(html);
}

app.get("/index.html", async (req, res) => {
  getHtml(req, res)
});

app.get("/h5.html", async (req, res) => {
  getHtml(req, res)
});

app.get("/h51.html", async (req, res) => {
  getHtml(req, res)
});

app.listen(port, () => {
  console.log("服务已开启");
});
